// pages/payfor/index.js
/** 
 * 需要一个目标日期，初始化时，先得出到当前时间还有剩余多少秒
 * 1.将秒数换成格式化输出为XX天XX小时XX分钟XX秒 XX
 * 2.提供一个时钟，每10ms运行一次，渲染时钟，再总ms数自减10
 * 3.剩余的秒次为零时，return，给出tips提示说，已经截止
 */

// 定义一个总毫秒数，以一分钟为例。TODO，传入一个时间点，转换成总毫秒数
var req = require('../../interfaceImpl.js');
var config = require('../../interfaceConfig.js');
var total_micro_second = 5 * 60 * 1000;
var strAppCode = config.SmallApp;
var finalMoney = 0;
var youhuilist =[];
var ReqmberAccount = ""; //优惠卷签名
var app =getApp();
var conpons = '';
/* 毫秒级倒计时 */
var nopass = false;
function count_down(that) {
  // 渲染倒计时时钟
  that.setData({
    clock: date_format(total_micro_second)
  });

  if (total_micro_second <= 0) {
    that.setData({
      clock: "已经截止",
      issuccess: false,
    });
    // timeout则跳出递归
    return;
  }
  setTimeout(function () {
    // 放在最后--
    total_micro_second -= 10;
    count_down(that);
  }
    , 10)
}

// 时间格式化输出，如03:25:19 86。每10ms都会调用一次
function date_format(micro_second) {
  // 秒数
  var second = Math.floor(micro_second / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位
  var min = fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
  // 秒位
  var sec = fill_zero_prefix((second - hr * 3600 - min * 60));// equal to => var sec = second % 60;
  // 毫秒位，保留2位
  var micro_sec = fill_zero_prefix(Math.floor((micro_second % 1000) / 10));

  return min + "分" + sec + "秒";
}

// 位数不足补零
function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}
var resGoodsSign = "";
var total = "";
var order = [];
var hasChooseSeat = [];
var plandate = '';
var showdate = '';
var cinema = '';
var lingshilist = [];
var buynum =[];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    clock: '',//支付剩余时间
    year: '',//当前的年份
    chkzuolist: [],//选择的座位
    chkzuo: '',//选择的座位
    // payforprice: 0,//付钱价格
    piaoprice: 0,//票价格
    tingnum: 0,//电影厅号
    dyid: 0,//电影id
    dyname: '',//电影名称
    yyid: 0, //影院id
    yyname: '', //影院名称
    chkday: '',//日期
    changciid: '',//场次id
    // time: '',//开场时间
    lingshilist: [],//零食列表
    zhifuqian: 0,//支付的钱
    open: false,//列表选项

    radioCheckVal: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    count_down(this);
    console.log(options)
    total = parseInt(options.TotalMoney);
    finalMoney = total;
    order = JSON.parse(options.order)[0];
    hasChooseSeat = JSON.parse(options.hasChooseSeat);
    plandate = JSON.parse(options.plandate);
    showdate = options.showdate;
    cinema = JSON.parse(options.cinema);
    var that = this;
    var chkzuo = "";
    lingshilist = [];
    for (var i = 0; i < hasChooseSeat.length; i++) {
      chkzuo += hasChooseSeat[i].SeatRow + "排" + hasChooseSeat[i].SeatCol + "座,"

    }
    //去除最后一个逗号
    chkzuo = chkzuo.substr(0, chkzuo.length - 1);
    console.log(plandate)
    that.setData({
      finalMoney: finalMoney,
      piaoprice: total,//票价
      // payforprice: options.sumprice,//付钱价格
      tingnum: plandate.HallName,//电影厅号
      // dyid: options.dyid,//电影id
      dyname: plandate.FilmName,//电影名称
      // yyid: options.yyid, //影院id
      yyname: plandate.CinemaName, //影院名称
      chkday: showdate,//日期
      time: plandate.PlayStartTime,//开场时间
      chkzuolist: hasChooseSeat,//选择的座位
      year: new Date().getFullYear(),//得到年份
      chkzuo: chkzuo,
      // zhifuqian: options.sumprice,//支付的钱
    })

    //计时器
    
    // var GoodsSign = "strAppCode=" + strAppCode;
    // return req.GetSignStr(GoodsSign).then(res => {
    //   if (res.data.success) {
    //     resGoodsSign = res.data.data
    //   }

    // }).then(() => {

      // return req.GetGoodList(strAppCode, resGoodsSign).then(res => {
      //   console.log(res)
      //   buynum=[];
      //   lingshilist = res.data.data;
      //   for (var i = 0; i < lingshilist.length; i++) {
      //     lingshilist[i].buynum = 0;
      //     buynum.push(0);
      //   }
      //   that.setData({
      //     lingshilist: lingshilist,
      //        buynum:buynum
      //   })
      // }).then(() => {
        
        //TODO请求 优惠卷
        var ReqmberAccountSign = "strAppCode=" + strAppCode + "OrderTicketID=" + order.OrderTicketID 
        req.GetSignStr(ReqmberAccountSign).then(res => {
          if (res.data.success) {
            ReqmberAccount = res.data.data
          }
        }).then(()=>{
          //请求优惠卷
          return req.mberAccount(strAppCode, order.OrderTicketID, ReqmberAccount,app.globalData.token).then(res=>{
           youhuilist=res.data.data;
            console.log(youhuilist)
            if (youhuilist.length>0){
              that.setData({ youhuilist: youhuilist })
            }
            else{
              that.setData({noyouhui:true})
            }
          })
        })


      // })
    // })


    //结束标识符
  },
 
  /**去支付**/
  gozhifu: function () {
      //TODO校验优惠卷
      if(nopass){
        wx.showModal({
          title: '提示',
          content: '优惠卷超过使用上限',
        })
        return false;
      }
    var that = this;
    var lingshiqian = 0;
    for (var j = 0; j < lingshilist.length; j++) {
      lingshilist[j].buynum = buynum[j]
      if (buynum[j] > 0) {
        lingshiqian += buynum[j] * parseInt(that.data.lingshilist[j].PriceSale);
      }
    }
    console.log(lingshiqian)
    console.log(lingshilist)
    //跳转到支付成功页面
    wx.navigateTo({
  
      url: '../payfor/paymethod?PayTotalPrice=' + finalMoney + '&&order=' + JSON.stringify(order) + '&&coupons=' + conpons +'&&youhuilist=' + JSON.stringify(youhuilist) + '&&hasChooseSeat=' + JSON.stringify(hasChooseSeat) + '&&plandate=' + JSON.stringify(plandate) + '&&showdate=' + showdate + '&&cinema=' + cinema + '&&ticketprice=' + total + '&&lingshilist=' + JSON.stringify(lingshilist)+''
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },



  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },
  showitem2: function () {
    this.setData({
      open2: !this.data.open
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  radioCheckedChange: function (e) {
    this.setData({
      radioCheckVal: e.detail.value
    })
  },

  choosecoupons:function(e){
    finalMoney = total;
        console.log(e.detail.value)
        var ticketnum = hasChooseSeat.length;
        if(e.detail.value.length>ticketnum){
          wx.showModal({
            title: '提示',
            content: '您购买了' + ticketnum + '张电影票' + '最多只能使用' + ticketnum+'张优惠卷',
          })
          nopass =true;
          return;
        }else{
          nopass =false;
          conpons = "";
          var ticketmoney = finalMoney/hasChooseSeat.length;
          finalMoney = finalMoney - ticketmoney *e.detail.value.length;
          this.setData({ finalMoney: finalMoney})
          for(var i = 0 ;i<e.detail.value.length;i++){
            if (i == e.detail.value.length -1){
              conpons += e.detail.value[i];
            }else{
              conpons += e.detail.value[i]+','
            }
          }

          console.log(conpons)
        }
  }
})